<template>
  <i-addressPicker :level="formData.channelLevel" v-model="showPicker" @confirm="confirm"
    :defaultCode="addressDefaultCode"></i-addressPicker>
  <i-drawer v-model="showChannelLevel" :list="channelLevel" @close="showChannelLevel = false" @confirm="handleConfirm"
    :confirm_title="false" :activeIndex="drawerActiveIndex"></i-drawer>
  <view class="add_address">
    <view class="view_form">
      <i-formItem title="申请等级" :border="false" :isRequire="true">
        <view class="inputs" @click="handleChannelLevel">
          <text v-if="addressLevelName" style="color: #16161f">{{
            addressLevelName
          }}</text>
          <text v-else>请选择申请地区等级</text>
          <view class="goto">
            <image src="../../static/images/goto_icon.png" mode=""></image>
          </view>
        </view>
      </i-formItem>
      <i-formItem title="申请地区" :border="false" :isRequire="true">
        <view class="inputs" @click="handleAddress">
          <text v-if="addressName" style="color: #16161f">{{
            addressName
          }}</text>
          <text v-else>请选择申请地区</text>
          <view class="goto">
            <image src="../../static/images/goto_icon.png" mode=""></image>
          </view>
        </view>
      </i-formItem>
      <i-formItem title="需购设备量" :border="false" v-if="channelDeviceCount.channelApplyDeviceCount">
        <input :disabled="true" placeholder-class="placeholder-class"
        v-model="channelDeviceCount.channelApplyDeviceCount" class="input" placeholder="请输入渠道推荐人ID" type="text" />
      </i-formItem>
      <i-formItem title="推荐人ID" :border="false" :isRequire="true">
        <input :disabled="editStatus" placeholder-class="placeholder-class"
          v-model="formData.channelAgentRecommendUserBusinessId" class="input" placeholder="请输入渠道推荐人ID" type="text" />
      </i-formItem>
      <i-formItem title="联系电话" :border="false" :isRequire="true">
        <input :disabled="editStatus" placeholder-class="placeholder-class" v-model="formData.contactMobile"
          class="input" placeholder="请输入联系电话" type="text" />
      </i-formItem>
      <i-formItem title="备注" :border="false" alignItems="flex-start">
        <textarea :disabled="editStatus" placeholder-class="placeholder-class" v-model="formData.remark"
          class="textarea" placeholder="请输入备注" />
      </i-formItem>
      <i-formItem v-if="formData.channelStatus === '2'" title="驳回原因" :border="false" alignItems="flex-start">
        <textarea :disabled="true" placeholder-class="placeholder-class" v-model="rejectReason" class="textarea"
          placeholder="请输入驳回原因" />
      </i-formItem>
    </view>
    <view class="submit">
      <i-buttons v-if="!editStatus" padding="18rpx" :radius="4" bgColor="#FB652E" color="#fff" @click="add">{{ 
        !formData.channelStatus  ? '提交' : '再次提交' }}</i-buttons>
      <div style="height: 32rpx"></div>
      <!-- 
      <i-buttons
        v-if="formData.id"
        padding="18rpx"
        :radius="4"
        bgColor="#fff"
        color="#333"
        @click="checklog"
        >申请记录</i-buttons
      > -->
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from "vue";
import { checkFormData, showTost } from "../../utils/common";
import { onLoad, onReady } from "@dcloudio/uni-app";
import {
  getChannelDeviceCount,
  applyChannel,
  getUserByBusinessId,
  getApplyDetail,
  editApplyChannel
} from "../../api/index";
import { channelLevel } from "../../utils/enums";
import { phoneReg } from "../../utils/regs";

interface AddRess {
  addrDetail: string;
  addrId?: string;
  cityCode: string;
  countyCode: string;
  isDefault: "0" | "1";
  provinceCode: string;
  userMobile: string;
  userName: string;
}

const showDel = ref(false);
const showPicker = ref(false);
const addrId = ref("");
const addressName = ref("");
const addressLevelName = ref("");
const showChannelLevel = ref(false);
const addressDefaultCode = ref<any[]>([])
const rejectReason = ref("")
const drawerActiveIndex = ref(-1)
const formData = reactive<any>({
  provinceCode: "",
  cityCode: "",
  countyCode: "",
  channelLevel: "",
  channelProvinceId: "",
  channelCityId: "",
  channelDistrictId: "",
  remark: "",
  contactMobile: "",
  channelAgentRecommendUserBusinessId: "",
  id: null,
  channelStatus: null,
});
const channelDeviceCount = reactive<{
  channelApplyDeviceCount: number,
  deviceCount: number
}>({
  channelApplyDeviceCount: 0,
  deviceCount: 0
})

const editStatus = computed(() => {
  return (formData.channelStatus === '1' || formData.channelStatus === '0') ? true : false
})

const handleChannelLevel = () => {
  if (editStatus.value) {
    uni.showToast({
      icon: "none",
      title: "信息审核中",
    });
    return
  }
  showChannelLevel.value = true;
}

const add = async () => {
  if (!addressName.value) {
    uni.showToast({
      icon: "none",
      title: "请选择申请地区",
    });
    return;
  }
  await checkFormData(formData, {
    channelLevel: {
      require: true,
      message: "请选择申请地区等级",
    },
    channelAgentRecommendUserBusinessId: {
      require: true,
      message: "请输入渠道推荐人",
    },
    contactMobile: {
      reg: phoneReg,
      message: "请输入正确联系电话",
    },
  });

  try {
    const { data } = await getUserByBusinessId(
      formData.channelAgentRecommendUserBusinessId
    );

    uni.showModal({
      title: "渠道推荐人信息",
      content: `昵称：${data.nickName}\n账号：${data.mobile}
      \n确定要提交吗？`,
      success: async (res) => {
        if (res.confirm) {
          if (formData.channelStatus === '2') {
            await editApplyChannel({ ...formData, rejectReason: '' });
          } else {
            await applyChannel(formData);
          }
          uni.showToast({
            icon: "none",
            title: "提交成功",
            duration: 2000,
            success: () => {
              setTimeout(() => {
                uni.navigateBack();
              }, 500);
            },
          });
        }
      },
    });
  } catch (error) {
    if (error.data.msg === "用户ID输入错误") {
      uni.showToast({
        icon: "none",
        title: "渠道推荐人不存在",
      });
    }
  }
};

const getChannelDeviceCountData = async () => {
  const { data } = await getChannelDeviceCount({
    channelProvinceId: formData.channelProvinceId,
    channelCityId: formData.channelCityId,
    channelDistrictId: formData.channelDistrictId,
    channelLevel: formData.channelLevel
  });
  channelDeviceCount.channelApplyDeviceCount = data.channelApplyDeviceCount
  channelDeviceCount.deviceCount = data.deviceCount
}

const confirm = (data: any) => {
  addressName.value =
    data.provinceName +
    (data.cityName ? `-${data.cityName}` : "") +
    (data.countyName ? `-${data.countyName}` : "");
  formData.channelProvinceId = data.province;
  formData.channelCityId = data.city;
  formData.channelDistrictId = data.county;
  getChannelDeviceCountData()
};


const handleConfirm = (value: any) => {
  formData.channelLevel = channelLevel[value].value;
  addressLevelName.value = channelLevel[value].label;
  addressName.value = "";
  formData.channelProvinceId = "";
  formData.channelCityId = "";
  formData.channelDistrictId = "";
  addressDefaultCode.value = []
  channelDeviceCount.channelApplyDeviceCount = 0
  channelDeviceCount.deviceCount = 0

};

const getApplyDetailData = async () => {
  const { data } = await getApplyDetail();
  if (!data) return
  formData.id = data.id;
  uni.setNavigationBarTitle({
    title: (data.status !== '0' || data.status === '2') ? "渠道代理申请" : "渠道代理审核中"
  })
  drawerActiveIndex.value = Number(data.channelLevel) - 1
  formData.contactMobile = data.contactMobile;
  formData.channelAgentRecommendUserBusinessId = data.channelAgentRecommendBusinessId;
  formData.channelLevel = data.channelLevel;
  addressLevelName.value =
    channelLevel?.find((i) => i.value == data?.channelLevel)?.label || "";
  formData.remark = data.remark;
  formData.channelStatus = data.channelStatus;
  if (data.channelStatus === '2') {
    rejectReason.value = data.rejectReason;
  }
  addressDefaultCode.value = [data.channelProvinceId, data.channelCityId, data.channelDistrictId]?.filter(i => i)
  confirm({
    ...data,
    provinceName: data.channelProvinceName,
    cityName: data.channelCityName,
    countyName: data.channelDistrictName,
    province: data.channelProvinceId,
    city: data.channelCityId,
    county: data.channelDistrictId,
  });
};

onLoad(() => {
  getApplyDetailData();
});

const handleAddress = () => {
  if (editStatus.value) {
    uni.showToast({
      icon: "none",
      title: "信息审核中",
    });
    return
  }
  if (formData.channelLevel) {
    showPicker.value = true;
  } else {
    uni.showToast({
      icon: "none",
      title: "请先选择申请地区等级",
      duration: 2000,
    });
    // showChannelLevel.value = true;
  }
};

// onReady(() => {
 
// })
</script>

<style lang="scss" scoped>
.add_address {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #fff;

  .view_form {
    padding: 32rpx;
    margin: 0 auto;
  }

  .input {
    width: 75%;
    font-size: 32rpx !important;
  }

  .inputs {
    width: 100%;
    color: #d1d1d6;
    @include flexRS;
    text {
      @include dfont(32rpx);
    }
    .goto {
      width: 32rpx;
      height: 32rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .submit {
    width: calc(100% - 64rpx);
    margin: 0 auto;
    margin-top: 32rpx;
  }

  .textarea {
    width: 100%;
    height: 80rpx;
    // color: #d1d1d6;
  }

}

::v-deep(.uni-modal__bd) {
  font-size: 28rpx;
}

:deep(.uni-textarea-textarea:disabled) {
  color: #666;
  background-color: #f5f5f5;
}
</style>
